package com.jftone.bh.app.util;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map.Entry;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jftone.config.Const;
import org.jftone.util.DataMap;
import org.jftone.util.EncryptUtil;
import org.jftone.util.IData;

public class WeixinConf {

	public static final IData<String, Object> wx = new DataMap<String, Object>(){{
		put("APP_ID", "wxe51c7aaf05d72b1c"); put("PAY_SECRET", "css8490389css8490389css8490389cs"); put("MCH_ID", "1528455451");put("NOTIFY_URL", "http://app.bh8341.com/notice/notifyWeixinApp");put("TOKEN", "TOKEN");
	}};

	public static final String DEVICE_INFO = "WEB";
	public static final String FEE_TYPE = "CNY";
	public static final String MD5 = "MD5";
	
	//微信支付类型
	public static final String TRADE_JSAPI = "JSAPI";
	public static final String TRADE_NATIVE = "NATIVE";
	public static final String TRADE_APP = "APP";
	public static final String RESULT_SUCC = "SUCCESS";		//微信支付成功返回值
	public static final String RESULT_FAIL = "FAIL";		//微信支付失败返回值
	public static final String ORDER_PAID = "ORDERPAID";		//订单已经支付
	
	public static final String JSAPI_TICKET_URL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=#ACCESS_TOKEN#&type=jsapi";
	//统一下单地址
	public static final String UNIFIED_ORDER_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
	//微信退款接口
	public static final String REFUND_URL = "https://api.mch.weixin.qq.com/secapi/pay/refund";
	//获取OPENID
	public static final String OPENID_URL = "https://api.weixin.qq.com/sns/jscode2session";
	
	
	/**
	 * 构建请求签名
	 * @param params
	 * @return
	 * @throws Exception
	 */
	public static IData<String, Object> buildRequestParam(IData<String, Object> params) throws Exception {
		IData<String, Object> filerData = new DataMap<String, Object>();
		filerData.put("sign", "sign");
		filerData.put("key", "key");
		return PayParamUtil.getFilterMap(params, filerData);
    }
	
	/**
	 * 获取签名
	 * @param params
	 * @param paySecret
	 * @return
	 * @throws Exception
	 */
	public static String getSignature(IData<String, Object> params,String paySecret) throws Exception {
    	String prestr = PayParamUtil.createLinkString(params); //把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
        String mysign = "";
        mysign = EncryptUtil.md5(prestr+"&key="+paySecret);
        return mysign;
    }
	
	/**
	 * 将请求参数转换为xml格式的string
	 * @param inParam
	 * @return
	 */
	public static String getRequestXml(IData<String, Object> inParam) {
		StringBuilder sb = new StringBuilder();
		sb.append("<xml>");
		for (Entry<String, Object> entry : inParam.entrySet()) {
			String key = entry.getKey();
			String value = String.valueOf(entry.getValue());
			if ("attach".equalsIgnoreCase(key) || "body".equalsIgnoreCase(key)
					|| "sign".equalsIgnoreCase(key)) {
				sb.append("<" + key + ">" + "<![CDATA[" + value + "]]></" + key+ ">");
			} else {
				sb.append("<" + key + ">" + value + "</" + key + ">");
			}
		}
		sb.append("</xml>");
		return sb.toString();
	}
	
	/**
	 *  <xml>
		   <appid>wx2421b1c4370ec43b</appid>
		   <attach>支付测试</attach>
		   <body>JSAPI支付测试</body>
		   <mch_id>10000100</mch_id>
		   <nonce_str>1add1a30ac87aa2db72f57a2375d8fec</nonce_str>
		   <notify_url>http://wxpay.weixin.qq.com/pub_v2/pay/notify.v2.php</notify_url>
		   <openid>oUpF8uMuAJO_M2pxb1Q9zNjWeS6o</openid>
		   <out_trade_no>1415659990</out_trade_no>
		   <spbill_create_ip>14.23.150.211</spbill_create_ip>
		   <total_fee>1</total_fee>
		   <trade_type>JSAPI</trade_type>
		   <sign>0CB01533B8C1EF103065174F50BCA001</sign>
		</xml>
	 * 解析xml,返回第一级元素键值对。如果第一级元素有子节点，则此节点的值是子节点的xml数据。
	 * @param strxml
	 * @return
	 * @throws JDOMException
	 * @throws IOException
	 */
	public static IData<String, Object> getXMLParseData(String strxml) throws IOException, JDOMException {
		if(null == strxml || "".equals(strxml)) {
			return null;
		}
		return getXMLParseData(new ByteArrayInputStream(strxml.getBytes(Const.CHARSET_UTF8)));
	}
	public static IData<String, Object> getXMLParseData(InputStream in) throws IOException, JDOMException {
		if(null == in) {
			return null;
		}
		IData<String, Object> data = new DataMap<String, Object>();
		SAXBuilder builder = new SAXBuilder();
		Document doc = builder.build(in);
		Element root = doc.getRootElement();
		List<Element> list = root.getChildren();
		for(Element e : list) {
			String key = e.getName();
			String str = "";
			//只解析第一级参数
			if(e.getChildren().isEmpty()) {
				str = e.getTextNormalize();
			} 
			data.put(key, str);
		}
		//关闭流
		in.close();
		return data;
	}

}
